package siteflash.controller;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import siteflash.data.SiteFlashPersistenceManage;
import siteflash.model.Game;

public class GameInfo extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
		
		resp.setHeader("Cache-Control", "public, max-age=7200");
		
		//Get parameter
		String path = ((HttpServletRequest) req).getRequestURI();
		String alias = path.toLowerCase().replaceAll("/game/", "");
		
		PersistenceManager psm = SiteFlashPersistenceManage.get().getPersistenceManager();
		Query query = psm.newQuery(Game.class);
		query.setFilter("alias == aliasParam");
		query.setRange(0, 1);
		query.declareParameters("java.lang.String aliasParam");
		List<Game> listResult = (List<Game>) query.execute(alias);
		Game game = new Game();
		
		if (listResult.size() > 0) 
		{
			game = (Game) listResult.get(0);
			//Update count played
			int played = game.getPlayed() + 1;
			game.setPlayed(played);
			psm.currentTransaction().begin();
			psm.makePersistent(game);
			psm.currentTransaction().commit();
			
			//Proccess tags
			req.setAttribute("game", game);
			
			try {
				//Set title
				req.setAttribute("title", "Play game " + listResult.get(0).getName() + " at Y1S.org");
				String keyword = listResult.get(0).getName();
				for(int i = 0; i < listResult.get(0).getTags().size(); i++) {
					keyword += listResult.get(0).getTags().get(i);
					if (i < listResult.get(0).getTags().size() - 1) {
						keyword += ", ";
					}
				}
				
				//Set attribute
				req.setAttribute("keyword", keyword);
				req.setAttribute("description", listResult.get(0).getDescription().getValue());
				
				req.getRequestDispatcher("/pages/game_info.jsp").forward(req, resp);
			} catch (Exception e) {
				//TODO: handle exception
				e.printStackTrace();
			}
		} 
		else 
		{
			try {
				//req.getRequestDispatcher("/pages/page_not_found.jsp").forward(req, resp);
				resp.sendRedirect("/");
			} catch (Exception e) {
				//TODO: handle exception
				e.printStackTrace();
			}
		}
	}
}
